<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {
  batchDeleteRateCurveRevaluations,
  createRateCurveRevaluation,
  deleteRateCurveRevaluation,
  fetchCurveDefinitionById,
  fetchRateCurveRevaluationsByCurveId,
  updateRateCurveRevaluation
} from '@/service/api/curve';

const route = useRoute();
const router = useRouter();

// 路由参数
const curveId = computed(() => Number(route.query.curveId));
const curveName = computed(() => (route.query.curveName as string) || '');

// 曲线定义信息
const curveInfo = ref<Api.Curve.CurveDefinition | null>(null);

// 表格数据
const loading = ref(false);
const dataSource = ref<Api.Curve.RateCurveRevaluation[]>([]);
const selectedRowKeys = ref<number[]>([]);

// 搜索参数
const searchParams = reactive({
  tenor: '',
  curveType: ''
});

// 弹窗状态
const modalVisible = ref(false);
const modalTitle = ref('');
const modalLoading = ref(false);
const editingId = ref<number | null>(null);

// 表单数据
const formData = reactive<Api.Curve.RateCurveRevaluationDTO>({
  mappingId: 1, // 默认映射ID，实际应该从曲线定义获取
  curveType: '',
  tenor: '',
  sourceValue: ''
});

/**
 * 将tenor字符串转换为可比较的数值（以天为单位）
 *
 * @param tenor 期限字符串，如 '1D', '1W', '1M', '1Y'
 * @returns 对应的天数
 */
function tenorTodays(tenor: string): number {
  if (!tenor) return 0;

  const match = tenor.match(/^(\d+)([DWMY])$/);
  if (!match) return 0;

  const [, num, unit] = match;
  const value = Number.parseInt(num, 10);

  switch (unit) {
    case 'D':
      return value;
    case 'W':
      return value * 7;
    case 'M':
      return value * 30;
    case 'Y':
      return value * 365;
    default:
      return 0;
  }
}

// 表格列定义
const columns: any[] = [
  {
    title: '数据ID',
    dataIndex: 'dataId',
    key: 'dataId',
    width: 100
  },
  {
    title: '期限',
    dataIndex: 'tenor',
    key: 'tenor',
    width: 120,
    sorter: (a: any, b: any) => {
      // 按期限长度排序
      return tenorTodays(a.tenor) - tenorTodays(b.tenor);
    },
    defaultSortOrder: 'ascend'
  },
  {
    title: '曲线类型',
    dataIndex: 'curveType',
    key: 'curveType',
    width: 150
  },

  {
    title: '数据源',
    dataIndex: 'sourceValue',
    key: 'sourceValue',
    width: 120
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
];

// 行选择配置
const rowSelection: any = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: any[]) => {
    selectedRowKeys.value = keys as number[];
  }
}));

// 获取曲线定义信息
async function getCurveInfo() {
  if (!curveId.value) return;

  try {
    const { data, error } = await fetchCurveDefinitionById(curveId.value);
    if (data) {
      curveInfo.value = data;
      // curveName现在是computed属性，不需要手动赋值
    } else if (error) {
      window.$message?.error(`获取曲线信息失败：${error.message}`);
    }
  } catch (error) {
    window.$message?.error(`获取曲线信息失败：${(error as any).message}`);
  }
}

// 获取曲线点数据
async function getData() {
  if (!curveId.value) return;

  loading.value = true;
  try {
    const { data, error } = await fetchRateCurveRevaluationsByCurveId(curveId.value);
    if (data) {
      let filteredData = data;

      // 前端筛选
      if (searchParams.tenor) {
        filteredData = filteredData.filter(item => item.tenor.toLowerCase().includes(searchParams.tenor.toLowerCase()));
      }
      if (searchParams.curveType) {
        filteredData = filteredData.filter(item =>
          item.curveType.toLowerCase().includes(searchParams.curveType.toLowerCase())
        );
      }

      dataSource.value = filteredData;
    } else if (error) {
      window.$message?.error(`获取曲线点数据失败：${error.message}`);
    }
  } catch (error) {
    window.$message?.error(`获取曲线点数据失败：${(error as any).message}`);
  } finally {
    loading.value = false;
  }
}

// 搜索
function handleSearch() {
  getData();
}

// 重置搜索
function handleReset() {
  Object.assign(searchParams, {
    tenor: '',
    curveType: ''
  });
  getData();
}

// 新建曲线点
function handleAdd() {
  modalTitle.value = '新建曲线点';
  editingId.value = null;
  Object.assign(formData, {
    mappingId: curveId.value || 1, // 使用曲线ID作为映射ID
    curveType: curveInfo.value?.curveType || '',
    tenor: '',
    sourceValue: ''
  });
  modalVisible.value = true;
}

// 编辑曲线点
/** 编辑曲线点弹窗：将当前行数据写入表单并打开弹窗 */
function handleEdit(record: Record<string, any>) {
  modalTitle.value = '编辑曲线点';
  editingId.value = Number(record.dataId);
  Object.assign(formData, {
    mappingId: Number(record.mappingId),
    curveType: String(record.curveType || ''),
    tenor: String(record.tenor || ''),
    sourceValue: String(record.sourceValue || '')
  });
  modalVisible.value = true;
}

// 删除曲线点
function handleDelete(record: Record<string, any>) {
  window.$modal?.confirm({
    title: '确认删除',
    content: `确定要删除期限为"${String(record.tenor || '')}"的曲线点吗？`,
    onOk: async () => {
      try {
        const { error } = await deleteRateCurveRevaluation(Number(record.dataId));
        if (!error) {
          window.$message?.success('删除成功');
          getData();
        } else {
          window.$message?.error(`删除失败：${error.message}`);
        }
      } catch (error) {
        window.$message?.error(`删除失败：${(error as any).message}`);
      }
    }
  });
}

// 批量删除
function handleBatchDelete() {
  if (selectedRowKeys.value.length === 0) {
    window.$message?.warning('请选择要删除的曲线点');
    return;
  }

  window.$modal?.confirm({
    title: '确认批量删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个曲线点吗？`,
    onOk: async () => {
      try {
        const { error } = await batchDeleteRateCurveRevaluations(selectedRowKeys.value);
        if (!error) {
          window.$message?.success('批量删除成功');
          selectedRowKeys.value = [];
          getData();
        } else {
          window.$message?.error(`批量删除失败：${error.message}`);
        }
      } catch (error) {
        window.$message?.error(`批量删除失败：${(error as any).message}`);
      }
    }
  });
}

// 保存表单
async function handleSave() {
  modalLoading.value = true;
  try {
    if (editingId.value) {
      // 编辑
      const { error } = await updateRateCurveRevaluation(editingId.value, formData);
      if (!error) {
        window.$message?.success('更新成功');
        modalVisible.value = false;
        getData();
      } else {
        window.$message?.error(`更新失败：${error.message}`);
      }
    } else {
      // 新建
      const { error } = await createRateCurveRevaluation(formData);
      if (!error) {
        window.$message?.success('创建成功');
        modalVisible.value = false;
        getData();
      } else {
        window.$message?.error(`创建失败：${error.message}`);
      }
    }
  } catch (error) {
    window.$message?.error(`操作失败：${(error as any).message}`);
  } finally {
    modalLoading.value = false;
  }
}

// 取消弹窗
function handleCancel() {
  modalVisible.value = false;
}

// 返回列表
function handleBack() {
  router.push('/valuation/curve-list');
}

// 初始化
onMounted(() => {
  if (curveId.value) {
    console.info('curveId', curveId.value);
    getCurveInfo();
    getData();
  } else {
    window.$message?.error('缺少曲线ID参数');
    handleBack();
  }
});

// 监听路由参数变化
watch(
  () => route.query.curveId,
  newCurveId => {
    if (newCurveId) {
      console.info('路由参数变化，新的curveId:', newCurveId);
      getCurveInfo();
      getData();
    }
  },
  { immediate: false }
);
</script>

<template>
  <div>
    <!-- 页面头部 -->
    <ACard class="mb-4">
      <div class="flex items-center justify-between">
        <div class="flex items-center gap-4">
          <AButton @click="handleBack">
            <template #icon>
              <icon-ic-round-arrow-back class="text-icon" />
            </template>
            返回列表
          </AButton>
          <ADivider type="vertical" />
          <div>
            <h2 class="mb-1 text-lg font-semibold">{{ curveName }} - 曲线点管理</h2>
            <div v-if="curveInfo" class="text-sm text-gray-500">
              曲线类型：{{ curveInfo.curveType }} | 货币：{{ curveInfo.currencyCode }}
              <span v-if="curveInfo.description">| {{ curveInfo.description }}</span>
            </div>
          </div>
        </div>
      </div>
    </ACard>

    <!-- 搜索区域 -->
    <ACard class="mb-4">
      <AForm layout="inline">
        <AFormItem label="期限">
          <AInput v-model:value="searchParams.tenor" placeholder="请输入期限" allow-clear @press-enter="handleSearch" />
        </AFormItem>
        <AFormItem label="曲线类型">
          <AInput
            v-model:value="searchParams.curveType"
            placeholder="请输入曲线类型"
            allow-clear
            @press-enter="handleSearch"
          />
        </AFormItem>

        <AFormItem>
          <ASpace>
            <AButton type="primary" @click="handleSearch">
              <template #icon>
                <icon-ic-round-search class="text-icon" />
              </template>
              搜索
            </AButton>
            <AButton @click="handleReset">
              <template #icon>
                <icon-ic-round-refresh class="text-icon" />
              </template>
              重置
            </AButton>
          </ASpace>
        </AFormItem>
        <ASpace>
          <AButton type="primary" @click="handleAdd">
            <template #icon>
              <icon-ic-round-add class="text-icon" />
            </template>
            新建曲线点
          </AButton>
          <AButton type="primary" danger :disabled="selectedRowKeys.length === 0" @click="handleBatchDelete">
            <template #icon>
              <icon-ic-round-delete class="text-icon" />
            </template>
            批量删除 ({{ selectedRowKeys.length }})
          </AButton>
        </ASpace>
      </AForm>
    </ACard>

    <!-- 操作区域 -->
    <ACard>
      <!-- 表格 -->
      <ATable
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :row-selection="rowSelection"
        :pagination="{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total: number) => `共 ${total} 条记录`,
          pageSizeOptions: ['10', '20', '50', '100'],
          defaultPageSize: 20
        }"
        row-key="dataId"
        :scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <ASpace>
              <AButton type="link" size="small" @click="handleEdit(record)">编辑</AButton>
              <AButton type="link" size="small" danger @click="handleDelete(record)">删除</AButton>
            </ASpace>
          </template>
        </template>
      </ATable>
    </ACard>

    <!-- 新建/编辑弹窗 -->
    <AModal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="modalLoading"
      @ok="handleSave"
      @cancel="handleCancel"
    >
      <AForm :model="formData" layout="vertical">
        <AFormItem label="期限" name="tenor" :rules="[{ required: true, message: '请输入期限' }]">
          <ASelect v-model:value="formData.tenor" placeholder="请选择期限">
            <ASelectOption value="1D">1天</ASelectOption>
            <ASelectOption value="1W">1周</ASelectOption>
            <ASelectOption value="1M">1月</ASelectOption>
            <ASelectOption value="3M">3月</ASelectOption>
            <ASelectOption value="6M">6月</ASelectOption>
            <ASelectOption value="1Y">1年</ASelectOption>
            <ASelectOption value="2Y">2年</ASelectOption>
            <ASelectOption value="3Y">3年</ASelectOption>
            <ASelectOption value="5Y">5年</ASelectOption>
            <ASelectOption value="10Y">10年</ASelectOption>
            <ASelectOption value="20Y">20年</ASelectOption>
            <ASelectOption value="30Y">30年</ASelectOption>
          </ASelect>
        </AFormItem>
        <AFormItem label="曲线类型" name="curveType" :rules="[{ required: true, message: '请选择曲线类型' }]">
          <ASelect v-model:value="formData.curveType" placeholder="请选择曲线类型">
            <ASelectOption value="ZERO_BOND">利率曲线</ASelectOption>
            <ASelectOption value="IRS">信用利差曲线</ASelectOption>
            <ASelectOption value="FX_SWAP">波动率曲线</ASelectOption>
            <ASelectOption value="DEP_GEN">远期曲线</ASelectOption>
          </ASelect>
        </AFormItem>

        <AFormItem label="数据源" name="sourceValue" :rules="[{ required: true, message: '请选择数据源' }]">
          <ASelect v-model:value="formData.sourceValue" placeholder="请选择数据源">
            <ASelectOption value="BLOOMBERG">Bloomberg</ASelectOption>
            <ASelectOption value="REUTERS">Reuters</ASelectOption>
            <ASelectOption value="WIND">Wind</ASelectOption>
            <ASelectOption value="MANUAL">手工输入</ASelectOption>
            <ASelectOption value="SYSTEM">系统计算</ASelectOption>
          </ASelect>
        </AFormItem>
      </AForm>
    </AModal>
  </div>
</template>

<style scoped>
.text-icon {
  font-size: 16px;
}

/* 紧凑表格样式 */
:deep(.ant-card-body) {
  display: grid;
}
:deep(.ant-table-tbody > tr > .ant-table-cell) {
  padding: 8px 16px !important;
}

:deep(.ant-table-thead > tr > th) {
  padding: 16px 16px !important;
}

:deep(.ant-table) {
  line-height: 1.2;
}
</style>
